<script setup>
import ip from '@/utils/baseURL.js';
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter() // 引入路由器

// 轮播图数据
const carouselImages = ref([])

// 键盘状态
const keyStatus = ref({
  shift: false,
  d: false,
  f: false,
  w: false
})

// 键盘按下事件处理
const handleKeyDown = (event) => {
  // 根据按键更新状态
  if (event.key === 'Shift') keyStatus.value.shift = true
  else if (event.key.toLowerCase() === 'd') keyStatus.value.d = true
  else if (event.key.toLowerCase() === 'f') keyStatus.value.f = true
  else if (event.key.toLowerCase() === 'w') keyStatus.value.w = true

  // 检查是否所有目标键都已按下
  if (keyStatus.value.shift && keyStatus.value.d && 
      keyStatus.value.f && keyStatus.value.w) {
    // 跳转到目标页面
    router.push('/user/dfw')
    // 重置键盘状态，防止连续触发
    resetKeyStatus()
  }
}

// 键盘释放事件处理
const handleKeyUp = (event) => {
  // 根据按键更新状态
  if (event.key === 'Shift') keyStatus.value.shift = false
  else if (event.key.toLowerCase() === 'd') keyStatus.value.d = false
  else if (event.key.toLowerCase() === 'f') keyStatus.value.f = false
  else if (event.key.toLowerCase() === 'w') keyStatus.value.w = false
}

// 重置键盘状态
const resetKeyStatus = () => {
  keyStatus.value = {
    shift: false,
    d: false,
    f: false,
    w: false
  }
}

// 获取轮播图数据
const fetchCarouselImages = async () => {
  try {
    const response = await axios.post(ip + '/inter/carousel/get',{})
    if (response.data.code === 200) {
      carouselImages.value = response.data.data.map(item => item.image)
      console.log('响应数据:', response.data)
      console.log('处理后的图片数组:', response.data.data.map(item => item.image))
    }
  } catch (error) {
    console.error('获取轮播图数据失败:', error)
    // 设置默认图片
    carouselImages.value = [
      'https://via.placeholder.com/1600x500/86B943/FFFFFF?text=智慧农业创新实验室',
      'https://via.placeholder.com/1600x500/86B943/FFFFFF?text=智慧农业创新实验室',
      'https://via.placeholder.com/1600x500/86B943/FFFFFF?text=智慧农业创新实验室',
      'https://via.placeholder.com/1600x500/86B943/FFFFFF?text=智慧农业创新实验室'
    ]
  }
}

// 删除原有的静态 news 和 notices 数据
// 添加新的响应式数据
const news = ref([])
const notices = ref([])

// 格式化时间数组为字符串
const formatTime = (timeArr) => {
    if (!timeArr || !Array.isArray(timeArr) || timeArr.length < 3) return '-';
    const [year, month, day] = timeArr;
    // 补充前导零
    const formattedMonth = String(month).padStart(2, '0');
    const formattedDay = String(day).padStart(2, '0');
    return `${year}-${formattedMonth}-${formattedDay}`;
}

// 获取新闻和通知数据
const fetchNewsAndNotices = async () => {
  try {
    const response = await axios.get(ip + '/inter/journalism/getJournalism')
    if (response.data.code === 200) {
      // 按时间倒序排序（假设 item.time 是 [年, 月, 日] 数组）
      const sortByTimeDesc = (a, b) => {
        if (!a.time || !b.time) return 0;
        // 转成时间戳比较
        const aTime = new Date(a.time[0], a.time[1] - 1, a.time[2]).getTime();
        const bTime = new Date(b.time[0], b.time[1] - 1, b.time[2]).getTime();
        return bTime - aTime;
      };

      const noticeData = response.data.data.filter(item => item.label === '通知公告').sort(sortByTimeDesc)
      const newsData = response.data.data.filter(item => item.label !== '通知公告').sort(sortByTimeDesc)
      
      // 格式化数据
      news.value = newsData.map(item => ({
        id: item.id,
        title: item.title,
        date: formatTime(item.time)
      }))
      
      notices.value = noticeData.map(item => ({
        id: item.id,
        title: item.title,
        date: formatTime(item.time)
      }))
    }
  } catch (error) {
    console.error('获取新闻和通知数据失败:', error)
    // 设置默认数据
    news.value = [
      { id: 1, title: '暂无新闻数据', date: '-' }
    ]
    notices.value = [
      { id: 1, title: '暂无通知数据', date: '-' }
    ]
  }
}

// 删除原有的静态 researchAreas 数据，改为响应式数据
const researchAreas = ref([])

// 添加获取研究方向的函数
const fetchResearchAreas = async () => {
  try {
    const response = await axios.get(`${ip}/inter/studio/getEssInfo`)
    if (response.data.code === 200) {
      // 过滤出 type 为 direction 的数据并格式化
      researchAreas.value = response.data.data
        .filter(item => item.type === 'direction')
        .map(item => ({
          id: item.id,
          title: item.remark,
          description: item.content
        }))
    }
  } catch (error) {
    console.error('获取研究方向失败:', error)
    // 设置默认数据
    researchAreas.value = [
      {
        id: 1,
        title: '暂无研究方向',
        description: '暂无描述'
      }
    ]
  }
}

const defaultAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
const displayedMembers = ref([])

// 获取团队成员数据
const fetchTeamMembers = async () => {
  try {
    const [teachersRes, studentsRes] = await Promise.all([
      axios.get(ip + '/inter/teacherInfo/getInfo'),
      axios.get(ip + '/inter/userInfo/getInfo')
    ])

    // 处理老师数据
    const teachers = teachersRes.data.code === 200 
      ? teachersRes.data.data.records.slice(0, 2).map(t => ({
          id: t.teacherId,
          name: t.teacherName,
          title: t.title,
          avatar: t.picture,
          type: 'teacher'
        })) 
      : []

    // 处理学生数据
const students = studentsRes.data.code === 200
  ? studentsRes.data.data.records
      .filter(s => s.position && s.position.includes('负责人')) // 模糊匹配 position 字段包含"负责人"
      .slice(0, 4 - teachers.length)
      .map(s => ({
        id: s.id,
        name: s.name,
        title: s.position,
        avatar: s.picture,
        type: 'student'
      }))
  : []

    displayedMembers.value = [...teachers, ...students].slice(0, 4)
    
  } catch (error) {
    console.error('获取团队成员失败:', error)
    
  }
}

// 在组件挂载时获取轮播图数据
onMounted(() => {
  fetchCarouselImages()
  fetchTeamMembers()
  fetchNewsAndNotices()
  fetchResearchAreas()
  
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyDown)
  window.addEventListener('keyup', handleKeyUp)
})

// 组件卸载时移除键盘事件监听器
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('keyup', handleKeyUp)
})

</script>
<template>
  <div class="home-container">
    <!-- 轮播图部分 -->
    <div class="banner-section">
      <el-carousel height="500px" :interval="5000">
        <el-carousel-item v-for="(url, index) in carouselImages" :key="index">
          <div class="banner-item" :style="{ backgroundImage: `url(${url})` }">
            <!-- 移除了文字内容 -->
          </div>          
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 新闻动态和通知公告 -->
      <div class="news-section">
        <div class="news-block">
          <div class="section-header">
            <h2>新闻动态</h2>
            <router-link to="/user/news" class="more-link">更多 ></router-link>
          </div>
          <ul class="news-list">
            <li v-for="item in news" :key="item.id" class="news-item">
              <router-link :to="`/user/news/detail?id=${item.id}`">
                <span class="news-title">{{ item.title }}</span>
                <span class="news-date">{{ item.date }}</span>
              </router-link>
            </li>
          </ul>
        </div>
        <div class="news-block">
          <div class="section-header">
            <h2>通知公告</h2>
            <router-link to="/user/news" class="more-link">更多 ></router-link>
          </div>
          <ul class="news-list">
            <li v-for="item in notices" :key="item.id" class="news-item">
              <router-link :to="`/user/news/detail?id=${item.id}`">
                <span class="news-title">{{ item.title }}</span>
                <span class="news-date">{{ item.date }}</span>
              </router-link>
            </li>
          </ul>
        </div>
      </div>

      <!-- 研究方向 -->
      <div class="research-section">
        <div class="section-header">
          <h2>研究方向</h2>
        </div>
        <div class="research-grid">
          <el-card v-for="item in researchAreas" :key="item.id" class="research-item">
            <div class="research-content">
              <div class="research-icon">
                <el-icon :size="40" color="#86B943">
                  <Monitor />
                </el-icon>
              </div>
              <h3>{{ item.title }}</h3>
              <p>{{ item.description }}</p>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 团队成员 -->
      <div class="team-section">
        <div class="section-header">
            <h2>团队成员</h2>
            <router-link to="/user/teachers" class="more-link">更多 ></router-link>
        </div>
        <div class="team-grid">
            <el-card 
                v-for="member in displayedMembers" 
                :key="member.id" 
                class="team-item"
            >
                <div class="member-content">
                    <div class="member-avatar">
                        <el-avatar :size="100" :src="member.avatar">
                            <template #default>
                                <div class="avatar-fallback">
                                    {{ member.name.slice(0, 1) }}
                                </div>
                            </template>
                        </el-avatar>
                    </div>
                    <h3>{{ member.name }}</h3>
                    <p class="member-title">
                        <el-tag 
                            :type="member.type === 'teacher' ? 'success' : 'info'" 
                            size="small"
                        >
                            {{ member.title }}
                        </el-tag>
                    </p>
                    <p class="member-type">
                        {{ member.type === 'teacher' ? '' : '' }}
                    </p>
                </div>
            </el-card>
        </div>
    </div>


    </div>
  </div>
</template>



<style lang="scss" scoped>
.home-container {
  .banner-section {
    margin-bottom: 40px;
    width: 100%;
    
    .banner-item {
      height: 100%;
      background-size: cover;
      background-position: center;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;
      text-align: center;

      h2 {
        font-size: 48px;
        margin-bottom: 20px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);  // 添加文字阴影增强可读性
      }

      p {
        font-size: 24px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);  // 添加文字阴影增强可读性
      }
    }
  }

  .main-content {
    width: 100%;
    margin: 0 auto;
    padding: 0;
    box-sizing: border-box;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    border-bottom: 2px solid #86B943;
    padding-bottom: 10px;

    h2 {
      font-size: 24px;
      color: #333;
      margin: 0;
      position: relative;
      padding-left: 15px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 20px;
        background-color: #86B943;
      }
    }

    .more-link {
      color: #86B943;
      text-decoration: none;
      &:hover {
        color: #86B943;
      }
    }
  }

  .news-section {
    display: flex;
    justify-content: space-between;
    gap: 40px;
    margin-bottom: 40px;

    .news-block {
        flex: 1;
        min-width: 0;
        background-color: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    }

    .news-list {
      list-style: none;
      padding: 0;
      margin: 0;

      .news-item {
        margin-bottom: 12px;
        
        a {
          display: flex;
          justify-content: space-between;
          text-decoration: none;
          color: #333;
          padding: 12px 16px;
          border-radius: 4px;
          background-color: #f8f8f8;
          transition: all 0.3s ease;
          border-left: 4px solid transparent;
          
          &:hover {
            background-color: #f0f7eb;
            border-left-color: #86B943;
            transform: translateX(5px);
            
            .news-title {
              color: #86B943;
            }
          }

          .news-title {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 20px;
            font-size: 15px;
            position: relative;
            padding-left: 15px;

            &::before {
              content: '';
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              width: 4px;
              height: 4px;
              border-radius: 50%;
              background-color: #86B943;
              opacity: 0.7;
            }
          }

          .news-date {
            color: #999;
            font-size: 14px;
            min-width: 90px;
            text-align: right;
          }
        }
      }
    }
  }

  .research-section {
    margin-bottom: 40px;

    .research-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
    }
  }

  .team-section {
    margin-bottom: 40px;

    .team-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
    }
  }
}

.team-section {
  margin: 40px 0;

  .team-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 20px;
  }

  .team-item {
    transition: transform 0.3s ease;

    &:hover {
      transform: translateY(-5px);
    }
  }

  .member-content {
    text-align: center;
    padding: 20px;

    .member-avatar {
      margin-bottom: 15px;
      
      .avatar-fallback {
        font-size: 24px;
        font-weight: bold;
        color: #fff;
        background: #86B943;
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    h3 {
      margin: 0 0 10px;
      font-size: 18px;
      color: #333;
    }

    .member-title {
      margin-bottom: 8px;
      
      .el-tag {
        border-radius: 12px;
      }
    }

    .member-type {
      color: #666;
      font-size: 14px;
    }
  }
}

.party-container {
    width: 100%;
    overflow-x: auto;
}

.section {
    margin-bottom: 30px;
}

.news-list .news-item {
    margin-bottom: 15px;
}

.news-image .el-image {
    height: 180px;
}

.page-header {
    margin-bottom: 30px;
}

@media (max-width: 1200px) {
  .home-container {
    overflow-x: auto;
    
    .main-content {
      width: 1200px;
    }
  }
}
</style>